/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.ebeitech.camera;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.hardware.Camera.*;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.*;
import android.view.View.MeasureSpec;
import android.view.View.OnClickListener;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.RelativeLayout.LayoutParams;

import com.ebeitech.doorapp.util.PublicUtil;
import com.ebeitech.library.constant.SPConstants;
import com.ebeitech.library.util.SPManager;
import com.ebeitech.doorapp.R;
import com.ebeitech.doorapp.view.OnInitializeListener;
import com.ebeitech.library.util.StringUtil;
import com.ebeitech.library.util.TimeUtil;
import com.ebeitech.library.util.ViewUtil;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

// ----------------------------------------------------------------------

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public class QPICameraFragment extends Fragment implements OnClickListener {

    private QPICameraPreview mPreview;
    Camera mCamera;
    int numberOfCameras;
    int cameraCurrentlyLocked;

    // The first rear facing camera
    int defaultCameraId;
    Size currentPictureSize = null;
    Size currentPreviewSize = null;
    private View start = null;
    private View topView = null;
    private static final String TAG = "QPICameraActivity";
    private static final int IMAGE_QUALITY = 80;
    private static final int ROTATION_ORIGI = 0;

    private static final int REQUEST_PREVIEW = 0X911;
    private static final int REQUEST_AUTO_FOCUS = 0X912;
    private Context mContext;
    //private TextView tvFlashLightSetting = null;
    private ImageView ivFlashLightSetting;
    private ImageView ivSettingSetting;
    private View use;
    private View delete;
    private View exit;
    private ViewGroup mContentView;
    private ListView mListView;
    private ImageView mImageView;
    private TextView useCount;

    private static final int AUTO_FOCUS_DELAY = 36 * 100;
    private Timer t = null;
    private boolean shouldTakePhoto = false;
    public static final String BITMAP_PATH_EXTRA = "bitmap path extra";
    private final String FLASH_LIGHT_SETTING = "FLASH_LIGHT_SETTING";
    private String[] settingLevels = null;
    private PopupWindow popupWindow = null;
    public static final String PICTURE_SIZE_SETTING = "PICTURE_SIZE_SETTING";
	private boolean isGranted = true;

    public static final int _LOW_ = 0x102;
    public static final int _MID_ = 0x103;
    public static final int _HIGH_ = 0x104;
    private List<Size> mSupporttedPreviewSize = null;
    private List<Size> mSupporttedPictureSize = null;
    private boolean isFocusing = false;
    private String picturePath;
    private Bitmap bitmap;
    private String mRepairOrderCode;
    private String locationName;

    private boolean flag = false;

    private SurfaceHolder holder;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int what = msg.what;
            if (REQUEST_PREVIEW == what) {
                goCameraPreview();
            } else if (REQUEST_AUTO_FOCUS == what) {
                if (mCamera != null) {
                    try {
                        Parameters parameters = mCamera.getParameters();
                        List<String> supportedFocusMode = parameters.getSupportedFocusModes();
                        if (supportedFocusMode != null && supportedFocusMode.contains(Parameters.FOCUS_MODE_AUTO)){
                            if (!isFocusing) {
                                isFocusing = true;
                                mCamera.autoFocus(autoFocusCb);
                                TimerTask task = new MyTimerTask();
                                t.schedule(task, AUTO_FOCUS_DELAY);
                            }
                            return;
                        }
                    } catch (RuntimeException e) {
                        // TODO: handle exception
                        isFocusing = false;
                        e.printStackTrace();
                    } catch (Exception ex) {
                        isFocusing = false;
                        ex.printStackTrace();
                    }

                    if (shouldTakePhoto) {
                        isFocusing = false;
                        takePhoto();
                        shouldTakePhoto = false;
                    }
                }
            }
        }
    };

    private boolean mCurrentOrient = false;
    private boolean mScreenProtrait = true;
    private int mLastRotation;
    private float mCurrentRotation;

    private GestureDetector mGestureDetector;

    private ScaleGestureDetector scaleGestureDetector;


    private OrientationEventListener mOrientationEventListener;
    private OnInitializeListener mInitializeListener;

    public void setOnInitializeListener(OnInitializeListener l) {
        mInitializeListener = l;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Hide the window title.
        mContext = getActivity();
        mRepairOrderCode = getActivity().getIntent().getStringExtra("repairOrderCode");
        locationName = getActivity().getIntent().getStringExtra("locationName");
        View view = LayoutInflater.from(mContext).inflate(R.layout.ebei_activity_media_camera, null);
        setupViews(view);
        setupFlashSettingLayout();
        mGestureDetector = new GestureDetector(mContext, mGestureDetectorListener);
        mScaleDetector = new ScaleGestureDetector(mContext, mScaleGestureListener);
        mOrientationEventListener = new MyOrientationEventListener(mContext);
        mOrientationEventListener.enable();

        if (!PublicUtil.checkSelfPermission(mContext, Manifest.permission.CAMERA)) {
			isGranted = false;
            PublicUtil.requestPermissions(this, Manifest.permission.CAMERA, 1);
		}

        return view;
    }

    //@Override
    public void onRequestPermissionsResult(int requestCode,
                                           String[] permissions, int[] grantResults) {
        // TODO Auto-generated method stub
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        isGranted = true;
        for (int i = 0; i < grantResults.length; i++) {
            if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                isGranted = false;
            }
        }
        if (isGranted) {
            if (mCamera == null) {
                onResume();
            }
        } else {
            ((Activity) mContext).finish();
        }
    }

    private GestureDetector.SimpleOnGestureListener mGestureDetectorListener = new GestureDetector.SimpleOnGestureListener() {
        @Override
        public boolean onSingleTapUp(MotionEvent event) {
            flag = false;
            int cameraCount = 0;
            CameraInfo cameraInfo = null;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
                cameraInfo = new CameraInfo();
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
                cameraCount = Camera.getNumberOfCameras();//得到摄像头的个数
            }
            for(int i = 0; i < cameraCount; i++) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
                    Camera.getCameraInfo(i, cameraInfo);//得到每一个摄像头的信息
                }
                if (defaultCameraId == 1) {
                    //现在是后置，变更为前置
                    if (cameraInfo.facing == CameraInfo.CAMERA_FACING_BACK) {//代表摄像头的方位，CAMERA_FACING_FRONT前置      CAMERA_FACING_BACK后置
                        mCamera.setPreviewCallback(null);
                        mCamera.stopPreview();//停掉原来摄像头的预览
                        mCamera.release();//释放资源
                        mCamera = null;//取消原来摄像头
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
                            mCamera = Camera.open(i);//打开当前选中的摄像头
                        }
                        try {
                            mCamera.setPreviewDisplay(mPreview.getHolder());//通过surfaceview显示取景画面
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        mPreview.switchCamera(mCamera);
//						mCamera.startPreview();//开始预览
                        defaultCameraId = 0;
                        mCamera.setDisplayOrientation(getCameraDisplayOrientation(getActivity(), defaultCameraId, mCamera));
                        //setupCurrentSize();
                        setUpCurrentPreviewSize();

                        break;
                    }
                } else {
                    //现在是前置， 变更为后置
                    if (cameraInfo.facing == CameraInfo.CAMERA_FACING_FRONT) {//代表摄像头的方位，CAMERA_FACING_FRONT前置      CAMERA_FACING_BACK后置
                        mCamera.setPreviewCallback(null);
                        mCamera.stopPreview();//停掉原来摄像头的预览
                        mCamera.release();//释放资源
                        mCamera = null;//取消原来摄像头
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
                            mCamera = Camera.open(i);//打开当前选中的摄像头
                        }
                        try {
                            mCamera.setPreviewDisplay(mPreview.getHolder());//通过surfaceview显示取景画面
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        mPreview.switchCamera(mCamera);
//						mCamera.startPreview();//开始预览
                        defaultCameraId = 1;
                        mCamera.setDisplayOrientation(getCameraDisplayOrientation(getActivity(), defaultCameraId, mCamera));
                        //setupCurrentSize();
                        setUpCurrentPreviewSize();
                        break;
                    }
                }
            }

            return false;
        }
    };

    private void setupViews(View view) {
        mCurrentRotation = -ROTATION_ORIGI;
        mPreview = (QPICameraPreview) view.findViewById(R.id.surfaceview);
        start = view.findViewById(R.id.start);
        topView = view.findViewById(R.id.view_top);
        start.setOnClickListener(this);
        PublicUtil.setRotation(start, mCurrentRotation);
        //tvFlashLightSetting = (TextView) view.findViewById(R.id.tvFlashSetting);
        ivFlashLightSetting = (ImageView) view.findViewById(R.id.ivFlashSetting);
        PublicUtil.setRotation(ivFlashLightSetting, mCurrentRotation);

        use = view.findViewById(R.id.view_use);
        useCount = (TextView) view.findViewById(R.id.use_count);
        PublicUtil.setRotation(use, mCurrentRotation);
        use.setOnClickListener(this);
        View useImage = view.findViewById(R.id.use);
        useImage.measure(0, 0);
        LayoutParams lp = (LayoutParams) use.getLayoutParams();
        lp.width = useImage.getMeasuredWidth();
        lp.height = useImage.getMeasuredHeight();
        use.setLayoutParams(lp);

        delete = view.findViewById(R.id.ivDelete);
        PublicUtil.setRotation(delete, mCurrentRotation);
        delete.setOnClickListener(this);
        mImageView = (ImageView) view.findViewById(R.id.imageview);
        ivSettingSetting = (ImageView) view.findViewById(R.id.ivSetting);
        exit = view.findViewById(R.id.exit);

        // Find the total number of cameras available
        numberOfCameras = Camera.getNumberOfCameras();
        settingLevels = getResources().getStringArray(R.array.ebei_camera_setting_levels);

        // Find the ID of the default camera
        CameraInfo cameraInfo = new CameraInfo();
        for (int i = 0; i < numberOfCameras; i++) {
            Camera.getCameraInfo(i, cameraInfo);
            if (cameraInfo.facing == CameraInfo.CAMERA_FACING_BACK) {
                defaultCameraId = i;
            }
        }

        ivSettingSetting.setOnClickListener(this);
        ivFlashLightSetting.setOnClickListener(this);
        exit.setOnClickListener(this);
//        mPreview.setOnClickListener(this);

        mPreview.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent event) {

                mGestureDetector.onTouchEvent(event);
                //双指缩放
                mScaleDetector.onTouchEvent(event);
                return false;
            }
        });
    }

    public float distance(MotionEvent event) {
        float dx = event.getX(1) - event.getX(0);
        float dy = event.getY(1) - event.getY(0);
        return (float) Math.sqrt(dx * dx + dy * dy);
    }

    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        
        if (!isGranted) {
            return;
        }

        // Open the default i.e. the first rear facing camera.
        initCamera(true);
        if (mInitializeListener != null) {
            mInitializeListener.onFinished();
        }
        if(mCamera != null){
            try {
                mCamera.startPreview();
            } catch (Exception e){

            }
            TimerTask task = new MyTimerTask();
            if (t == null) {
                t = new Timer();
            }
            t.schedule(task, AUTO_FOCUS_DELAY);
        }

    }

    private class MyTimerTask extends TimerTask {

        public void run() {
            Message message = handler.obtainMessage(REQUEST_AUTO_FOCUS);
            handler.sendMessage(message);
        }

    };

    @SuppressLint("NewApi")
    class MyOrientationEventListener extends OrientationEventListener {

        public MyOrientationEventListener(Context context) {
            super(context);
            // TODO Auto-generated constructor stub
        }

        @Override
        public void onOrientationChanged(int rotation) {
            // TODO Auto-generated method stub
            if (((rotation >= 0) && (rotation <= 45)) || (rotation >= 315)||((rotation>=135)&&(rotation<=225))) {//portrait
                // protrait
                mCurrentOrient = true;
                if (mCurrentOrient != mScreenProtrait) {
                    mScreenProtrait = mCurrentOrient;
                    Log.i(TAG ,"竖屏");
                    int widgetRotation = -ROTATION_ORIGI;
                    mCurrentRotation = widgetRotation;
                    PublicUtil.setRotation(start, widgetRotation);
                    PublicUtil.setRotation(ivFlashLightSetting, widgetRotation);
                    PublicUtil.setRotation(use, widgetRotation);
                    PublicUtil.setRotation(delete, widgetRotation);
                    if(popupWindow != null && popupWindow.isShowing()) {
                        onSettingLayoutClicked(null);
                    }
                    mLastRotation = rotation;
                }
            } else if (((rotation > 45) && (rotation < 135))
                    || ((rotation > 225) && (rotation < 315))) {
                // landscape
                mCurrentOrient = false;
                if (Math.abs(mLastRotation - rotation) > 90 || mCurrentOrient != mScreenProtrait) {
                    mScreenProtrait = mCurrentOrient;
                    Log.i(TAG ,"横屏");
                    int widgetRotation = 0;
                    if(rotation < 135) {
                        widgetRotation = 270 - ROTATION_ORIGI;
                    } else {
                        widgetRotation = 90 - ROTATION_ORIGI;
                    }
                    mCurrentRotation = widgetRotation;
                    PublicUtil.setRotation(start, widgetRotation);
                    PublicUtil.setRotation(ivFlashLightSetting, widgetRotation);
                    PublicUtil.setRotation(use, widgetRotation);
                    PublicUtil.setRotation(delete, widgetRotation);
                    if(popupWindow != null && popupWindow.isShowing()) {
                        onSettingLayoutClicked(null);
                    }
                    mLastRotation = rotation;
                }
            }
        }

    };

    private int getCameraDisplayOrientation(Activity activity, int cameraId, Camera camera) {
        CameraInfo info = new CameraInfo();
        Camera.getCameraInfo(cameraId, info);
        int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
        int degrees = 0;
        switch (rotation) {
            case Surface.ROTATION_0:
                degrees = 0;
                break;
            case Surface.ROTATION_90:
                degrees = 90;
                break;
            case Surface.ROTATION_180:
                degrees = 180;
                break;
            case Surface.ROTATION_270:
                degrees = 270;
                break;
            default:
                break;
        }
        int result = 0;
        if(info.facing == CameraInfo.CAMERA_FACING_FRONT) {
            result = (info.orientation + degrees) % 360;
            result = (360 - result) % 360;
        } else {
            result = (info.orientation - degrees + 360) % 360;
        }
        return result;
    }

    private void initCamera(boolean shouldRecycle) {
        if (shouldRecycle) {
            recycle();
        }
        if (mCamera == null) {
            try {
                mCamera = Camera.open();
            } catch (Exception e) {
                // TODO: handle exception
                recycle();
                return;
            }
            if(mCamera == null){
                return;
            }
            cameraCurrentlyLocked = defaultCameraId;
            mPreview.setCamera(mCamera);
            //sortSize(mPreview.mSupportedPictureSizes);
            mSupporttedPreviewSize = mPreview.mSupportedPreviewSizes;
            sortSize(mSupporttedPreviewSize);
            mSupporttedPictureSize = mPreview.mSupportedPictureSizes;
            sortSize(mSupporttedPictureSize);

            mCamera.setDisplayOrientation(getCameraDisplayOrientation(getActivity(), cameraCurrentlyLocked, mCamera));
            //setupCurrentSize();
            setUpCurrentPreviewSize();
        }
    }

    public void setUpCurrentPreviewSize() {
        //图片大小应该根据视图大小选取，否则比例会失真

        List<Size> sizes = new ArrayList<Size>();
        if(mSupporttedPreviewSize!=null){
            for (int i = 0; i < mSupporttedPreviewSize.size(); i++) {
                Size size = mSupporttedPreviewSize.get(i);
                if(mSupporttedPictureSize.contains(size)) {
                    sizes.add(size);
                }
            }
        }

        List<Size> pictureSizes = new ArrayList<Size>();
        if (sizes.size() == 0 && mSupporttedPreviewSize!=null) {
            // 如果没有一组对的上，就找成比例的
            for (int i = 0; i < mSupporttedPreviewSize.size(); i++) {
                Size size = mSupporttedPreviewSize.get(i);
                for (Size pictureSize : mSupporttedPictureSize) {
                    if (size.width * pictureSize.height == size.height * pictureSize.width) {
                        sizes.add(size);
                        pictureSizes.add(pictureSize);
                        break;
                    }
                }
            }
        }

        int setting = SPManager.getInstance(mContext).get(PICTURE_SIZE_SETTING, _LOW_);
        int index = 0;
        for (int i = 0; i < sizes.size(); i++) {
            Size size = sizes.get(i);
            if (size.height * size.width >= 640 * 480) {
                index = i;
                break;
            }
        }

        if (sizes.size() == 0) {
            if(mSupporttedPreviewSize !=null){
                // 如果还是没有一组对的上
                currentPreviewSize = mSupporttedPreviewSize.get(mSupporttedPreviewSize.size() / 2);
            }
            if(mSupporttedPictureSize !=null){
                currentPictureSize = mSupporttedPictureSize.get(mSupporttedPictureSize.size() / 2);
            }

        } else {
            switch (setting) {
                case _LOW_:
                    currentPreviewSize = sizes.get(index);
                    break;
                case _MID_:
                    currentPreviewSize = sizes.get(index + (sizes.size() - 1 - index) / 2);
                    break;
                case _HIGH_:
                    int i = index + (sizes.size() - 1 - index) / 2 + 1;
                    if(i > sizes.size() - 1) {
                        i = sizes.size() - 1;
                    }
                    currentPreviewSize = sizes.get(i);
                    break;
            }

            if (pictureSizes.size() > 0) {
                index = sizes.indexOf(currentPreviewSize);
                currentPictureSize = pictureSizes.get(index);
            } else {
                currentPictureSize = currentPreviewSize;
            }
        }


        if (mCamera != null) {
            Parameters parameters = mCamera.getParameters();
            parameters.setPictureFormat(ImageFormat.JPEG);
            parameters.set("jpeg-quality", IMAGE_QUALITY);
            if (currentPreviewSize != null) {
                parameters.setPreviewSize(currentPreviewSize.width, currentPreviewSize.height);
            }
            if (currentPictureSize != null) {
                parameters.setPictureSize(currentPictureSize.width, currentPictureSize.height);
            }

            try {
                mCamera.setParameters(parameters);
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }

            mPreview.requestLayout();
        }

        if(currentPreviewSize != null) {
            Log.i(TAG, "setUpCurrentPreviewSize : currentPreviewSize width = " + currentPreviewSize.width + " , height = " +
                    currentPreviewSize.height);
        }
        if(currentPictureSize != null) {
            Log.i(TAG, "setUpCurrentPreviewSize : currentPictureSize width = " + currentPictureSize.width + " , height = " +
                    currentPictureSize.height);
        }
        Parameters parameters = mCamera.getParameters();
        Log.i(TAG, "setUpCurrentPreviewSize : Parameters PreviewSize width ==> " +
                parameters.getPreviewSize().width + " , height = " +
                parameters.getPreviewSize().height);
        Log.i(TAG, "setUpCurrentPreviewSize : Parameters PictureSize width ==> " +
                parameters.getPictureSize().width + " , height = " +
                parameters.getPictureSize().height);
    }

    private boolean isPictureSizeValid(Size pictureSize) {
        Parameters parameters = mCamera.getParameters();
        return parameters.getPictureSize().equals(pictureSize);
    }


    public void setupCurrentSize() {
        // TODO Auto-generated method stub
        int setting = SPManager.getInstance(mContext).get(PICTURE_SIZE_SETTING, _LOW_);
        int i = -1;
        int length = mSupporttedPictureSize.size();
        int dt = 0;
        if (length > 5) {
            dt = (length - 3) / 2;
        }

        switch (setting) {
            case _LOW_:
                i = 0;
                break;
            case _MID_:
                i = 1;
                break;
            case _HIGH_:
                i = 2;
                break;
        }

        if (-1 != i) {
            int index = i;
            i += dt;
            if (i > length - 1) {
                i = length - 1;
            }
            currentPictureSize = mSupporttedPictureSize.get(i);
            if (currentPictureSize.height * currentPictureSize.width < 640 * 480) {
                int j = i + 1;
                for (; j < length; j++) {
                    Size s = mSupporttedPictureSize.get(j);
                    if (640 * 480 < s.height * s.width) {
                        break;
                    }
                }
                j += index;
                if (j >= length) {
                    j = length - 1;
                }
                currentPictureSize = mSupporttedPictureSize.get(j);
            }
        } else {
            currentPictureSize = null;
        }
        if (mCamera != null) {
            Parameters parameters = mCamera.getParameters();
            parameters.setPictureFormat(ImageFormat.JPEG);
            parameters.set("jpeg-quality", IMAGE_QUALITY);
            if (currentPictureSize != null) {
                parameters.setPictureSize(currentPictureSize.width,
                        currentPictureSize.height);
            }
            try {
                mCamera.setParameters(parameters);
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }
        }
    }

    private void sortSize(List<Size> sizes) {
        // TODO Auto-generated method stub
		/*mSupporttedPictureSize = sizes;
		Collections.sort(mSupporttedPictureSize, new SizeComparator());
		return;*/
        if(sizes!=null&&sizes.size()!=0)
            Collections.sort(sizes, new SizeComparator());
    }

    private class SizeComparator implements Comparator<Size> {

        public int compare(Size o1, Size o2) {
            return (o1.height * o1.width) - (o2.height * o2.width);
        }
    }

    @Override
    public void onPause() {
        // TODO Auto-generated method stub
        super.onPause();

        // Because the Camera object is a shared resource, it's very
        // important to release it when the activity is paused.
        if (t != null) {
            t.cancel();
            t = null;
        }

        isFocusing = false;

        recycle();

    }

    private void recycle() {
        if (mCamera != null) {
            mPreview.setCamera(null);
            mCamera.setPreviewCallback(null);
            mCamera.stopPreview();
            mCamera.release();
            mCamera = null;
        }
    }

    public void onFlashSettingLayoutClicked(View v) {

        String flashLightSetting = SPManager.getInstance(mContext).get(FLASH_LIGHT_SETTING, Parameters.FLASH_MODE_OFF);
        String mode = flashLightSetting;
        if (Parameters.FLASH_MODE_OFF.equals(flashLightSetting)) {
            mode = Parameters.FLASH_MODE_TORCH;
        } else if (Parameters.FLASH_MODE_TORCH.equals(flashLightSetting)) {
            mode = Parameters.FLASH_MODE_OFF;
        }
        if (mCamera != null) {
            Parameters parameters = mCamera.getParameters();
            List<String> supportedFlashMode = parameters
                    .getSupportedFlashModes();
            if (supportedFlashMode != null && supportedFlashMode.contains(mode)) {
                try {
                    parameters.setFlashMode(mode);
                    mCamera.setParameters(parameters);
                    SPManager.getInstance(mContext).put(FLASH_LIGHT_SETTING, mode);
                    setupFlashSettingLayout();
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(mContext, R.string.ebei_flashlight_unsurpported,
                            Toast.LENGTH_SHORT).show();
                    ;
                }
            } else {
                Toast.makeText(mContext, R.string.ebei_flashlight_unsurpported,
                        Toast.LENGTH_SHORT).show();
                ;
            }
        }
    }

    private void setupFlashSettingLayout() {
        String flashLightSetting = SPManager.getInstance(mContext).get(FLASH_LIGHT_SETTING, Parameters.FLASH_MODE_OFF);
        Resources res = getResources();
        int textColor = res.getColor(R.color.ebei_golden);
        if (Parameters.FLASH_MODE_OFF.equals(flashLightSetting)) {
            //tvFlashLightSetting.setText(R.string.open);
            ivFlashLightSetting.setImageResource(R.drawable.ebei_camera_flash_off);
            //ivFlashLightSetting.setImageResource(R.drawable.flash_light_on);
            //tvFlashLightSetting.setTextColor(textColor);
        } else if (Parameters.FLASH_MODE_TORCH.equals(flashLightSetting)) {
            textColor = res.getColor(R.color.ebei_video_text_color);
            //tvFlashLightSetting.setText(R.string.closed);
            ivFlashLightSetting.setImageResource(R.drawable.ebei_camera_flash_on);
            //ivFlashLightSetting.setImageResource(R.drawable.flash_light_off);
            //tvFlashLightSetting.setTextColor(textColor);
        }
    }

    @SuppressLint("NewApi")
    public void onSettingLayoutClicked(View view) {
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
        }
        //int[] xy = new int[2];
        //view.getLocationOnScreen(xy);
        //int x = xy[0];
        //int y = xy[1];
        int x = 0;
        int y = 0;
        Log.i("tiger log", "before x: " + x + " y: " + y);
        final LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
        mContentView = (ViewGroup) inflater.inflate(R.layout.ebei_view_media_list_camera_setting, null);
        mListView = (ListView) mContentView.findViewById(R.id.settingListView);
        //mContentView.findViewById(R.id.settingListView).setVisibility(View.GONE);
        //mListView = new ListView(this);
        BaseAdapter adapter = new BaseAdapter() {

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                // TODO Auto-generated method stub
                if (convertView == null) {
                    convertView = inflater.inflate(R.layout.ebei_view_list_title_item, null);
                }
                TextView tv = (TextView) convertView.findViewById(R.id.tvName);
                tv.setText(settingLevels[position]);
                //tv.setBackgroundResource(R.drawable.camera_setting_bg);
                convertView.setBackgroundResource(R.drawable.ebei_camera_setting_bg);
                return convertView;
            }

            @Override
            public long getItemId(int position) {
                // TODO Auto-generated method stub
                return position;
            }

            @Override
            public Object getItem(int position) {
                // TODO Auto-generated method stub
                if (settingLevels != null)
                    return settingLevels[position];
                return null;
            }

            @Override
            public int getCount() {
                // TODO Auto-generated method stub
                if (settingLevels != null)
                    return settingLevels.length;
                return 0;
            }
        };

        mListView.setAdapter(adapter);
        mListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                // TODO Auto-generated method stub
                popupWindow.dismiss();
                popupWindow = null;
                int setting = _LOW_;
                if (0 == position) {
                    setting = _LOW_;
                } else if (1 == position) {
                    setting = _MID_;
                } else if (2 == position) {
                    setting = _HIGH_;
                }
                SPManager.getInstance(mContext).put(PICTURE_SIZE_SETTING, setting);
                // setSurfaceSize();
                //setupCurrentSize();
                setUpCurrentPreviewSize();
            }
        });

        mContentView.measure(
                MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
                MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
        // x -= listView.getMeasuredWidth();

		/*mListView.measure(
				MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
				MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));*/

        Log.i("tiger log", "listView width: " + mContentView.getMeasuredWidth());
        // Log.i("tiger log", "after x: " + x + " y: " + y);
        DisplayMetrics size = ViewUtil.getScreenSize(getActivity());
        Log.i("tiger log", "screen width: " + size.widthPixels + " Screen height: "
                + size.heightPixels);

		/*popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

			@Override
			public void onDismiss() {
				// TODO Auto-generated method stub
				ivSettingSetting.setima
			}
		});*/
        updateView();
    }

    private void updateView() {
        int width = 0, height = 0;
        View childView = getActivity().getLayoutInflater().inflate(R.layout.ebei_view_list_title_item, null);
        childView.measure(0, 0);

        height = childView.getMeasuredHeight() * settingLevels.length;
        width = height;
        int topHeight = (int) getResources().getDimension(R.dimen.ebei_title_bar_image_size);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0, 0);
        //mContentView.setLayoutParams(new LayoutParams(height, width));
        lp.width = width;
        lp.height = height;
        if(mScreenProtrait) {
            mListView.setLayoutParams(lp);
            //mContentView.addView(mListView, lp);
            mContentView.measure(0, 0);
            int diff = mContentView.getMeasuredHeight() - childView.getMeasuredHeight();
            popupWindow = ViewUtil
                    .showPopupWindow(mContentView, topView, width,
                            mContentView.getMeasuredHeight(), Gravity.LEFT | Gravity.TOP, 10, topHeight);
        } else {
            PublicUtil.setRotation(mListView, getRotation());
            mListView.setLayoutParams(lp);
            //mContentView.addView(mListView, lp);
            mContentView.measure(0, 0);
            int diff = mContentView.getMeasuredHeight() - childView.getMeasuredHeight();
			/*if(start.getRotation() == 90) {
				lp.leftMargin = -(height - width) / 2;
				lp.topMargin = (height - width) / 2;
				lp.rightMargin = 0;
				lp.bottomMargin = 0;
			} else {
				lp.leftMargin = -(height - width) / 2;
				lp.topMargin = (height - width) / 2;
				lp.rightMargin = 0;
				lp.bottomMargin = 0;
			}*/
            //lp.height = LinearLayout.LayoutParams.WRAP_CONTENT;
            mListView.setLayoutParams(lp);
            popupWindow = ViewUtil
                    .showPopupWindow(mContentView, topView, height,
                            mContentView.getMeasuredHeight(), Gravity.LEFT | Gravity.TOP, 10, topHeight);
        }
    }

    private void goCameraPreview() {
        Intent intent = new Intent(mContext,QPIPicturePreviewActivity.class);
        Bundle b = new Bundle();
        b.putString(BITMAP_PATH_EXTRA, picturePath);
        b.putString("repairOrderCode", mRepairOrderCode);
        b.putString("locationName", locationName);
        intent.putExtras(b);
        // intent.putExtra(QPIConstants.PHOTOS_KEY, photos);
        startActivityForResult(intent, REQUEST_PREVIEW);
    }

    private void onDeleteClicked(View v) {
        if(!StringUtil.isStringNullOrEmpty(picturePath)) {
            File f = new File(picturePath);
            if (f.exists()) {
                try {
                    f.delete();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }

        ivFlashLightSetting.setVisibility(View.VISIBLE);
        ivSettingSetting.setVisibility(View.VISIBLE);
        start.setEnabled(true);
        start.setOnClickListener(this);
        use.setVisibility(View.GONE);
        delete.setVisibility(View.GONE);
        mImageView.setVisibility(View.GONE);
        mPreview.setVisibility(View.VISIBLE);

        isFocusing = false;
        initCamera(true);
        mPreview.switchCamera(mCamera);
    }

    public void onStartClicked(View v) {
        start.setEnabled(false);
        use.setEnabled(false);

        //setupCurrentSize();
        shouldTakePhoto = true;
        Message message = handler.obtainMessage(REQUEST_AUTO_FOCUS);
        handler.sendMessage(message);
    }

    public void onExitClicked(View v) {
        onBackPressed();
    }

    /*
     * (non-Javadoc)
     *
     * @see android.app.Activity#onBackPressed()
     */
    public void onBackPressed() {
        // super.onBackPressed();
        ArrayList<String> photos = getFilePaths();
        if (photos != null && photos.size() > 0) {
            Intent data = new Intent();
            data.putExtra(SPConstants.FILE_TYPE, SPConstants.REQUEST_CAMERA);
            data.putExtra(SPConstants.PHOTOS_KEY, photos);
            data.putExtra("isFromCamera", true);
            data.putExtra("isCancel", true);
            ((Activity) mContext).setResult(Activity.RESULT_OK, data);
        } else {
            ((Activity) mContext).setResult(Activity.RESULT_CANCELED, null);
        }
        SPManager.getInstance(mContext).removeKeyAndValue(SPConstants.PHOTOS_KEY);
        recycle();
        ((Activity) mContext).finish();
    }

    private ArrayList<String> getFilePaths() {
        String filePaths = SPManager.getInstance(mContext).get(SPConstants.PHOTOS_KEY, "");
        if (!StringUtil.isStringNullOrEmpty(filePaths)) {
            ArrayList<String> photos = new ArrayList<String>();
            if (filePaths
                    .contains(QPIPicturePreviewActivity.FILE_PATH_SEPARATOR)) {
                String[] paths = filePaths
                        .split(QPIPicturePreviewActivity.FILE_PATH_SEPARATOR);
                for (String path : paths) {
                    photos.add(path);
                }
            } else {
                photos.add(filePaths);
            }
            return photos;
        }
        return null;
    }



    private void takePhoto() {
        if (mCamera != null) {
            try {
                mCamera.takePicture(shuttercallback, rawcallback,picturecallback);
                use.setEnabled(false);
                start.setEnabled(false);
                start.setClickable(false);
                start.setOnClickListener(null);
            } catch (Exception ex) {
                ex.printStackTrace();
                Toast.makeText(mContext, R.string.ebei_camera_error_happen, Toast.LENGTH_LONG).show();
                if (mCamera != null) {
                    try {
                        Parameters params = mCamera.getParameters();
                        params.setFlashMode(Parameters.FLASH_MODE_OFF);
                        mCamera.setParameters(params);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                onBackPressed();
            }
        }
    }

    private ShutterCallback shuttercallback = new ShutterCallback() {

        @Override
        public void onShutter() {
            // TODO Auto-generated method stub

        }
    };
    private PictureCallback rawcallback = new PictureCallback() {

        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            // TODO Auto-generated method stub

        }
    };
    private PictureCallback picturecallback = new PictureCallback() {

        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            // TODO Auto-generated method stub
            Bitmap bm = null;
            try {
                bm = BitmapFactory.decodeByteArray(data, 0, data.length);
            } catch (OutOfMemoryError e) {
                // TODO: handle exception
                start.setClickable(true);
                start.setOnClickListener(QPICameraFragment.this);
                Toast.makeText(mContext, R.string.ebei_out_of_memery, Toast.LENGTH_LONG).show();
                e.printStackTrace();
                return;
            } catch (Exception ex) {
                ex.printStackTrace();
                start.setClickable(true);
                start.setOnClickListener(QPICameraFragment.this);
                Toast.makeText(mContext, R.string.ebei_out_of_memery, Toast.LENGTH_LONG).show();
                return;
            }

            if(mCamera!=null) {
                Size pictureSize = mCamera.getParameters().getPictureSize();
                Log.i(TAG, "onPictureTaken : currentPictureSize width = " + pictureSize.width +
                        " , height = " + pictureSize.height);
            }
            try {
                String picturePath = PublicUtil.getAppFile(mContext) + "/" + TimeUtil.getCurrentTime("yyyyMMdd_HHmmss") + ".jpg";
                File picFile = new File(picturePath);

                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(picFile));

                //旋转图片到正确的位置
                Matrix matrix = new Matrix();
                CameraInfo info = new CameraInfo();
                Camera.getCameraInfo(defaultCameraId, info);
                matrix.setRotate(info.orientation - getRotation());
                Bitmap bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
                bitmap.compress(Bitmap.CompressFormat.JPEG, IMAGE_QUALITY, bos);
                Log.i(TAG,
                        "bitmap : width = " + bitmap.getWidth() + " , height = " + bitmap.getHeight());

                if (picFile.exists()) {
                    QPICameraFragment.this.picturePath = picturePath;

                    handler.sendEmptyMessage(REQUEST_PREVIEW);
                } else {
                    use.setEnabled(true);
                    start.setEnabled(true);
                    Toast.makeText(mContext,
                            R.string.ebei_camera_error_happen, Toast.LENGTH_LONG).show();
                }

            } catch (OutOfMemoryError e) {
                use.setEnabled(true);
                start.setEnabled(true);
                start.setClickable(true);
                start.setOnClickListener(QPICameraFragment.this);
                Toast.makeText(mContext, R.string.ebei_out_of_memery, Toast.LENGTH_LONG).show();
                e.printStackTrace();
            } catch (Exception e) {
                use.setEnabled(true);
                start.setEnabled(true);
                start.setClickable(true);
                start.setOnClickListener(QPICameraFragment.this);
                Toast.makeText(mContext, R.string.ebei_out_of_memery, Toast.LENGTH_LONG).show();
                e.printStackTrace();
            }

        }
    };
    
    public void onSingleTapUp(MotionEvent e) {
    	mGestureDetectorListener.onSingleTapUp(e);
    }
    
    public void onScale(ScaleGestureDetector detector) {
    	mScaleGestureListener.onScale(detector);
    }

    public boolean isSupportZoom() {
        boolean isSuppport = false;
        try {
            if (mCamera.getParameters().isZoomSupported()) {
                isSuppport = true;
            }
        }catch (Exception e){
            if (!flag){
                Toast.makeText(mContext,"在此模式下无法进行缩放", Toast.LENGTH_SHORT).show();
                flag = true;
            }else {

            }
        }
        return isSuppport;
    }

    private void setZoom(boolean Lenth) {
        if (isSupportZoom()) {
            try {
                Parameters params = mCamera.getParameters();
                final int MAX = params.getMaxZoom();
                if (MAX == 0) return;

                int zoomValue = params.getZoom();
//                Trace.Log("-----------------MAX:" + MAX + "   params : " + zoomValue);
                if (Lenth) {
                    if (zoomValue >= MAX) {
                        return;
                    }
                    zoomValue += 2;
                } else {
                    if (zoomValue <= 0) {
                        return;
                    }
                    zoomValue -= 2;
                }

                params.setZoom(zoomValue);
                mCamera.setParameters(params);
            } catch (Exception e) {
//                Trace.Log("--------exception zoom");
                e.printStackTrace();
            }
        } else {
//            Trace.Log("--------the phone not support zoom");
        }
    }
    //监听图片缩放
    private ScaleGestureDetector mScaleDetector;

    //当前的缩放比例
    private float mScaleFactor = 1.0f;
    float startLenth = 0f;
    float endLenth;
    private ScaleGestureDetector.SimpleOnScaleGestureListener mScaleGestureListener = new ScaleGestureDetector.SimpleOnScaleGestureListener() {
        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            mScaleFactor = 1.0f;
            if (isSupportZoom()) {
                endLenth = detector.getCurrentSpan();
                if (detector.getCurrentSpan()-detector.getPreviousSpan()>0){
                    setZoom(true);
                }else {
                    setZoom(false);
                }
//                if (detector.isInProgress()){
//                    mScaleFactor *= detector.getScaleFactor();
//                    Log.i("@@@@",detector.getScaleFactor()+"");
//                    //缩放倍数范围：0.3～3
//                    Parameters params = mCamera.getParameters();
//                    final int MAX = params.getMaxZoom();
//                    mScaleFactor = Math.max(0.3f, Math.min(mScaleFactor, MAX));
//
//                    params.setZoom((int) mScaleFactor);
//                    mCamera.setParameters(params);
//                    return  false;
//                }
            }else {
                if (!flag){
                    Toast.makeText(mContext,"在此模式下无法进行缩放", Toast.LENGTH_SHORT).show();
                    flag = true;
                }else {

                }
            }

            return false;
        }
    };

    private AutoFocusCallback autoFocusCb = new AutoFocusCallback() {

        @Override
        public void onAutoFocus(boolean success, Camera camera) {
            // TODO Auto-generated method stub
            // mCamera.setOneShotPreviewCallback(null);
            isFocusing = false;
            if (shouldTakePhoto) {
                takePhoto();
                shouldTakePhoto = false;
            }
        }
    };

    public static Bitmap zoomImg(Bitmap bm, int newWidth, int newHeight) {
        // get the width and height of the original picture
        int width = bm.getWidth();
        int height = bm.getHeight();
        // find the scale rate
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // set the scale matrix parameters
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // create new bitmap
        Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix,true);
        return newbm;
    }

    //获取旋转角度
    private float getRotation() {
        return mCurrentRotation;
    }

    /*
     * (non-Javadoc)
     *
     * @see android.app.Activity#onDestroy()
     */
    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        if (mCamera != null) {
            try {
                Parameters params = mCamera.getParameters();
                params.setFlashMode(Parameters.FLASH_MODE_OFF);
                mCamera.setParameters(params);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        recycle();
        SPManager.getInstance(mContext).removeKeyAndValue(SPConstants.PHOTOS_KEY);

        if(bitmap != null) {
            bitmap.recycle();
            bitmap = null;
            System.gc();
        }

        if (mOrientationEventListener != null) {
            mOrientationEventListener.disable();
        }
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if (v == start) {
            onStartClicked(v);
        } else if(v == delete) {
            onDeleteClicked(v);
        } else if(v == use) {
            start.setEnabled(false);
            use.setEnabled(false);
            ArrayList<String> photos = getFilePaths();
            if (photos != null && photos.size() > 0) {
                Intent intent = new Intent();
                intent.putExtra(SPConstants.FILE_TYPE, SPConstants.REQUEST_CAMERA);
                intent.putExtra(SPConstants.PHOTOS_KEY, photos);
                intent.putExtra("isFromCamera", true);
                ((Activity) mContext).setResult(Activity.RESULT_OK, intent);
            }
            recycle();

            SPManager.getInstance(mContext).removeKeyAndValue(SPConstants.PHOTOS_KEY);
            ((Activity) mContext).finish();
            //goCameraPreview();
        } else if(v == ivSettingSetting) {
            onSettingLayoutClicked(ivSettingSetting);
        } else if(v == ivFlashLightSetting) {
            onFlashSettingLayoutClicked(ivFlashLightSetting);
        } else if(v == exit) {
            onExitClicked(exit);
        }
//        else if (v == mPreview){
////			mPreview.changeCamera();
//
//            //切换前后摄像头
//            int cameraCount = 0;
//            Camera.CameraInfo cameraInfo = null;
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
//                cameraInfo = new Camera.CameraInfo();
//            }
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
//                cameraCount = Camera.getNumberOfCameras();//得到摄像头的个数
//            }
//            for(int i = 0; i < cameraCount; i++) {
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
//                    Camera.getCameraInfo(i, cameraInfo);//得到每一个摄像头的信息
//                }
//                if (defaultCameraId == 1) {
//                    //现在是后置，变更为前置
//                    if (cameraInfo.facing == CameraInfo.CAMERA_FACING_BACK) {//代表摄像头的方位，CAMERA_FACING_FRONT前置      CAMERA_FACING_BACK后置
//                        mCamera.setPreviewCallback(null);
//                        mCamera.stopPreview();//停掉原来摄像头的预览
//                        mCamera.release();//释放资源
//                        mCamera = null;//取消原来摄像头
//                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
//                            mCamera = Camera.open(i);//打开当前选中的摄像头
//                        }
//                        try {
//                            mCamera.setPreviewDisplay(mPreview.getHolder());//通过surfaceview显示取景画面
//                        } catch (IOException e) {
//                            // TODO Auto-generated catch block
//                            e.printStackTrace();
//                        }
//                        mPreview.switchCamera(mCamera);
////						mCamera.startPreview();//开始预览
//                        defaultCameraId = 0;
//                        mCamera.setDisplayOrientation(getCameraDisplayOrientation(getActivity(), defaultCameraId, mCamera));
//                        //setupCurrentSize();
//                        setUpCurrentPreviewSize();
//
//                        break;
//                    }
//                } else {
//                    //现在是前置， 变更为后置
//                    if (cameraInfo.facing == CameraInfo.CAMERA_FACING_FRONT) {//代表摄像头的方位，CAMERA_FACING_FRONT前置      CAMERA_FACING_BACK后置
//                        mCamera.setPreviewCallback(null);
//                        mCamera.stopPreview();//停掉原来摄像头的预览
//                        mCamera.release();//释放资源
//                        mCamera = null;//取消原来摄像头
//                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
//                            mCamera = Camera.open(i);//打开当前选中的摄像头
//                        }
//                        try {
//                            mCamera.setPreviewDisplay(mPreview.getHolder());//通过surfaceview显示取景画面
//                        } catch (IOException e) {
//                            // TODO Auto-generated catch block
//                            e.printStackTrace();
//                        }
//                        mPreview.switchCamera(mCamera);
////						mCamera.startPreview();//开始预览
//                        defaultCameraId = 1;
//                        mCamera.setDisplayOrientation(getCameraDisplayOrientation(getActivity(), defaultCameraId, mCamera));
//                        //setupCurrentSize();
//                        setUpCurrentPreviewSize();
//                        break;
//                    }
//                }
//            }
//
////			mCamera.setDisplayOrientation(getCameraDisplayOrientation(getActivity(), 0, mCamera));
//        }
    }

    /*
     * (non-Javadoc)
     *
     * @see android.app.Activity#onActivityResult(int, int,
     * android.content.Intent)
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        boolean shouldFinish = true;
        use.setEnabled(true);
        start.setEnabled(true);
        start.setClickable(true);
        start.setOnClickListener(this);
        isFocusing = false;
        if (REQUEST_PREVIEW == requestCode) {
            if (QPIPicturePreviewActivity.RESULT_NEXT == resultCode) {
                shouldFinish = false;
            } else if (QPIPicturePreviewActivity.RESULT_RECAPURE == resultCode) {
                shouldFinish = false;
            }

            if (shouldFinish) {
                ArrayList<String> photos = getFilePaths();
                if (photos != null && photos.size() > 0) {
                    Intent intent = new Intent();
                    intent.putExtra(SPConstants.FILE_TYPE, SPConstants.REQUEST_CAMERA);
                    intent.putExtra(SPConstants.PHOTOS_KEY, photos);
                    intent.putExtra("isFromCamera", true);
                    ((Activity) mContext).setResult(Activity.RESULT_OK, intent);
                }
                recycle();

                SPManager.getInstance(mContext).removeKeyAndValue(SPConstants.PHOTOS_KEY);
                ((Activity) mContext).finish();
            } else {
                ArrayList<String> photos = getFilePaths();
                if (photos != null && photos.size() > 0) {
                    useCount.setText(photos.size() + "");
                    use.setVisibility(View.VISIBLE);
                } else {
                    use.setVisibility(View.INVISIBLE);
                }
            }
        }
    }

}

// ----------------------------------------------------------------------

